﻿using System;
using System.Data;
using ExampleApplication.DL;
using ExampleApplication.Models.Base;
using SQLPXBase.Factory;
using SQLPXBase.Factory.Keys;
using SQLPXBase.Factory.Keys.KeyModels;

namespace ExampleApplication.Models
{
    internal class Person:BaseModel
    {
        internal Person(ModelFactory<sql> factory) : base(factory)
        {
        }

        public string Name { get; set; }
        public string Surname { get; set; }
        public DateTime DateOfBirth { get; set; }

        public LazyKey<Articolo, sql> Prodotto { get; protected set; }

        #region Overrides of FactorizableModel<sql>

        protected override void Load(PrimaryKey id)
        {
            InitializeFromDB(factory.ProxyManager.GetProxy().Person.Load((LongPK) id));
        }

        protected override void InitializeFromDB(DataRow rw)
        {
            SetPK(new LongPK((long) rw["id"]));

            Name = rw["name"] as string ?? "";
            Surname = rw["surname"] as string ?? "";
            DateOfBirth = (DateTime) rw["dateOfBirth"];

            Prodotto.Id = new Articolo.ArtPK(rw, "ArtK1", "ArtK2", "ArtK3");
        }

        #endregion

        

        // Lazy cars collection
        private CarCollection carsOwned = null;
        public CarCollection CarsOwned
        {
            get
            {
                if (!Id.IsEmpty && carsOwned == null)
                    carsOwned = factory.List<CarCollection, Car>(new CarCollection.ListByOwner((LongPK) Id));
                return carsOwned;
            }
        }
    }

    internal class PersonCollection:ModelCollection<Person>
    {
        #region Loaders

        public class List : IModelCollectionLoader<Person, sql>
        {
            public DataTable Load(ModelFactory<sql> factory)
            {
                return factory.ProxyManager.GetProxy().Person.List();
            }
        }

        #endregion
    }
}
